﻿using Dapper;
using Entity;
using IRealize;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Data.SqlClient;
using Realize;
using System.Data;
using System.Threading.Tasks;

namespace WebApplication9.Controllers.ClientSet
{
    public class EJJGSZController : Controller
    {
        private readonly ILogger<EJJGSZController> logger;
        private readonly IConfiguration configuration;

        public EJJGSZController(ILogger<EJJGSZController> logger,IConfiguration configuration)
        {
            this.logger = logger;
            this.configuration = configuration;
        }
        public IActionResult Index()
        {
            return View();
        }
        public async Task<IActionResult> Index2(int pageSize,int currentPage)
        {
            //CFSK cFSK = new CFSK();
            //List<Config_File_Second_Kind> zhi = await cFSK.SelectCFSKAsync(configuration["SqlServer"]);
            //return Ok(new
            //{
            //    list = zhi
            //});
            string sqlserver = configuration["SqlServer"];
            using (SqlConnection conn = new SqlConnection(sqlserver))
            {
                //@pageSize, @tableName, @keyName, @currentPage, @rows
                //分页存储过程
                DynamicParameters param = new DynamicParameters();
                param.Add("@pageSize", pageSize);
                param.Add("@keyName", "fsk_id");
                param.Add("@tableName", "config_file_second_kind");
                param.Add("@currentPage", currentPage);
                param.Add("@totalRows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[proc_FenYedd] @pageSize, @keyName, @tableName, @currentPage, @totalRows out";
                List<Config_File_Second_Kind> list = conn.Query<Config_File_Second_Kind>(sql, param).ToList();

                FenYe<Config_File_Second_Kind> fenYecs = new FenYe<Config_File_Second_Kind>();
                fenYecs.List = list;
                fenYecs.Rows = param.Get<int>("totalRows");
                //return fenYecs;
                return Json(fenYecs);

            }
        }
        public async Task<IActionResult> AddCFSK()
        {

            ICFFK cFFK = new CFFK();
            List<Config_File_First_Kind> cfk = await cFFK.SelectCFFKAsync(configuration["SqlServer"]);
            SelectList selectListItems = new SelectList(cfk, "first_kind_name", "first_kind_name");
            ViewBag.D = selectListItems;
            return View();

        }
        [HttpPost]
        public async Task<IActionResult> AddCFSK(Config_File_Second_Kind cfsk)
        {

            //操作
            ICFSK cFSK = new CFSK();
            int js = await cFSK.AddCFSKAsync(cfsk, configuration["SqlServer"]);
            if (js > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }

        }

        public async Task<IActionResult> Update(int id)
        {
            ICFSK cFSK = new CFSK();
            ViewData.Model = await cFSK.SelectCFSKIDAsync(id, configuration["SqlServer"]);

            CFFK cFFK = new CFFK();
            List<Config_File_First_Kind> cfk = await cFFK.SelectCFFKAsync(configuration["SqlServer"]);
            SelectList selectListItems = new SelectList(cfk, "first_kind_name", "first_kind_name");
            ViewBag.K = selectListItems;

            return View();
        }
        [HttpPost]
        public async Task<IActionResult> Update(Config_File_Second_Kind cfsk,int id)
        {
            //根据参数做修改操作
            ICFSK cFSK = new CFSK();
            int result = await cFSK.UpdateCFSKAsync(cfsk, configuration["SqlServer"], id);
            if (result > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                return View();

            }
        }

        public async Task<IActionResult> Delete(int id)
        {
            ICFSK cFSK = new CFSK();
            int zhi = await cFSK.DeleteCFSKAsync(id, configuration["SqlServer"]);
            if (zhi > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                return View();
            }

        }



        // 获取级联数据（I级→II级→III级）
        [HttpGet("GetFirstLevelOrgData")]
        public async Task<IActionResult> GetFirstLevelOrgData()
        {
            using (var connection = new SqlConnection(configuration["SqlServer"]))
            {
                await connection.OpenAsync();

                // 查询I级机构
                var firstKinds = await connection.QueryAsync<dynamic>(
                    "SELECT first_kind_id AS id, first_kind_name AS name FROM config_file_first_kind");

                // 构建级联数据结构
                var result = new List<dynamic>();

                foreach (var firstKind in firstKinds)
                {
                    // 查询对应的II级机构
                    var secondKinds = await connection.QueryAsync<dynamic>(
                        "SELECT second_kind_id AS id, second_kind_name AS name " +
                        "FROM config_file_second_kind " +
                        "WHERE first_kind_id = @Id",
                        new { Id = firstKind.id });

                    var secondList = new List<dynamic>();

                    foreach (var secondKind in secondKinds)
                    {
                        // 查询对应的III级机构
                        var thirdKinds = await connection.QueryAsync<dynamic>(
                            "SELECT third_kind_id AS id, third_kind_name AS name " +
                            "FROM config_file_third_kind " +
                            "WHERE second_kind_id = @Id",
                            new { Id = secondKind.id });

                        secondList.Add(new
                        {
                            id = secondKind.id,
                            name = secondKind.name,
                            children = thirdKinds
                        });
                    }

                    result.Add(new
                    {
                        id = firstKind.id,
                        name = firstKind.name,
                        children = secondList
                    });
                }

                return Ok(result);
            }
        }




    }
}
